// AMapLoader.js
export default function loadQQMap(key) {
  return new Promise((resolve, reject) => {
    if (window.qq && window.qq.maps) {
      resolve(window.qq);
      return;
    }

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://map.qq.com/api/js?v=2.exp&key=${key}&callback=initMapCallback`;

    // 添加一个全局的回调函数用于API加载完成时调用
    window.initMapCallback = () => {
      if (window.qq && window.qq.maps) {
        resolve(window.qq);
      } else {
        reject(new Error('Failed to initialize QQ Map API'));
      }
      // 清除全局回调函数以避免内存泄漏
      delete window.initMapCallback;
    };

    script.onerror = () => {
      reject(new Error('Failed to load QQ Map API'));
    };

    document.head.appendChild(script);
  });
}
